trap '' 1
#!/usr/bin/bash
#pro_base="$(cd `dirname $(readlink -f $0)`;pwd)"        # program base directory. readlink是为了获取脚本的真实路径
#pro_root="${pro_base##*/}"                              # 我的程序的根目录名字.   readlink使得ln创建的软链也能正确地执行
#pro_name="$(readlink -f $0 | sed 's#^.*/##; s#.sh$##')" # 删除'/'前的路径,删除'.sh'


Help "$@"
[[ $# -ne 1 ]] && Usage && exit 1

Ps_tomcat(){
    ps -ef |egrep "CMD|=${tomcatPath}" |grep -v grep
}

Stop_tomcat(){
    local tom_ps count pid
    tom_ps="$(Ps_tomcat)"
    count="$(echo "${tom_ps}"|wc -l)"
    case ${count} in
    2)
        pid=$(echo "${tom_ps}" | awk '/tomcat/{print $2}')
#        Eval_cont "bash ${tomcatPath}/bin/shutdown.sh"  # 根据catalina.out日志,这两行的效果貌似相同的
        kill ${pid}                                    # 根据catalina.out日志,这两行的效果貌似相同的
        while [[ $(echo "${tom_ps}" | wc -l) -gt 1 ]]
        do
            echo "${tom_ps}"
            sleep 2
            tom_ps="$(ps -wwfp ${pid})"
        done
        POk "tomcat 实例已关闭"
        ;;
    1)
        PInfo "系统中似乎并不存在 tomcat 实例"
        Eval_cont "ps -ef |egrep 'CMD|${tomcatPath}'"
        ;;
    *)
        PWarn "可能存在下面多个 tomcat 实例,请关闭多余的实例"
        echo "${tom_ps}" && return 1
        ;;
    esac
}

Start_tomcat(){
    local tom_ps
    tom_ps="$(Ps_tomcat)"
    if [[ `echo "${tom_ps}"|wc -l` -gt 1 ]]; then
        PWarn "tomcat 实例可能已启动,进程信息如下:"
        echo "${tom_ps}"
        return 1
    else
        cmd="find ${tomcatLogPath} -mtime +60 -delete"
        PInfo "delete logs before 60 days ago..."
        Eval_cont "${cmd}"
        Eval_exit "bash ${tomcatPath}/bin/startup.sh"
    fi
}

! [[ -d "${tomcatPath}" ]] && PError "[指定的 tomcat 目录不存在]: ${tomcatPath}" && exit 1
! [[ -d "${tomcatLogPath}" ]] && PError "[tomcat 的日志目录不存在]: ${tomcatLogPath}" && exit 1

case $1 in
    -k|stop|sto)
        Eval_exit Stop_tomcat ;;
    -s|start|sta|star)
        Eval_cont Start_tomcat ;;
    -r|restart|r|re|res|rest|resta|restar)
        Eval_exit Stop_tomcat
        Eval_cont Start_tomcat ;;
    *)
    Usage && exit 1 ;;
esac
